<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        ref="queryForm"
        :inline="true"
        :model="queryParams"
        v-show="showSearch"
        @submit.native.prevent
        label-width="65px"
      >
        <el-form-item label="脱敏对象" prop="apiUrl">
          <common-input
            v-model="queryParams.apiUrl"
            clearable
            @enter="handleQuery"
            :maxlength="256"
          />
          <!-- <el-select
            style="width: 100%"
            v-model="queryParams.apiUrl"
            filterable
            v-loadmore="loadMore"
            remote
            reserve-keyword
            @focus="focus"
            :remote-method="remoteMethod"
            :loading="selectLoading"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="(item, index) in urlOptions"
              :key="index"
              :label="item.url"
              :value="item.url"
            ></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="类型" prop="strategyType">
          <el-select style="width: 100%" v-model="queryParams.strategyType">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="通配" :value="1"></el-option>
            <el-option label="接口" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select style="width: 100%" v-model="queryParams.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="(item, index) in typeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <el-row :gutter="10" slot="tools">
      <el-col :span="1.5" v-hasPermi="['apisecurity:sensitivestrategy:add']">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['apisecurity:sensitivestrategy:remove']">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleDelete"
          :disabled="multiple"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      slot="content"
      :data="list"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="脱敏对象"
        show-overflow-tooltip
        align="left"
        prop="apiUrl"
      />
      <el-table-column
        label="类型"
        show-overflow-tooltip
        align="left"
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.strategyType == 1 ? "通配" : "接口" }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        width="200"
      />
      <el-table-column label="状态" align="center" prop="status" width="160">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === 0">启用</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="160">
        <template slot-scope="scope">
          <template>
            <el-button type="text" @click="handleInfo(scope.row)"
              >详情
            </el-button>
            <el-button
              type="text"
              @click="handleEdit(scope.row)"
              v-hasPermi="['apisecurity:sensitivestrategy:edit']"
              >编辑
            </el-button>
            <el-button
              type="text"
              @click="handleShake(scope.row)"
              :disabled="scope.row.isDisabledForShake"
              v-hasPermi="['apisecurity:sensitivestrategy:status']"
              >{{ scope.row.status === 1 ? "启用" : "停用" }}
            </el-button>
            <el-button
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['apisecurity:sensitivestrategy:remove']"
              >删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <common-edit-dialog
      :title="isEdit ? '编辑脱敏策略' : '新增脱敏策略'"
      :visible.sync="open"
      :button-loading="submitLoading"
      @cancel="cancel"
      @submit="submitForm"
      ref="editDialog"
    >
      <el-form
        :model="form"
        label-width="80px"
        ref="form"
        :rules="rules"
        style="padding-top: 12px"
        @submit.native.prevent
      >
        <el-form-item
          label="类型"
          prop="strategyType"
          :rules="rules.strategyType"
        >
          <el-radio-group v-model="form.strategyType" @change="changeType">
            <el-radio label="1">通配</el-radio>
            <el-radio label="0">接口</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="脱敏对象"
          prop="apiUrl"
          :rules="form.strategyType === '0' ? rules.apiUrl : rules.apiUrl2"
        >
          <el-select
            v-if="form.strategyType === '0'"
            style="width: 100%"
            v-model="form.apiUrl"
            filterable
            v-loadmore="loadMore"
            remote
            reserve-keyword
            @focus="focus"
            :remote-method="remoteMethod"
            :loading="selectLoading"
            @change="changeUrl"
            clearable
          >
            <el-option
              v-for="(item, index) in urlOptions"
              :key="index"
              :label="item.url"
              :value="item.url"
            ></el-option>
          </el-select>
          <common-input
            v-else
            v-model="form.apiUrl"
            :verify="false"
            placeholder="/system/**"
          />
        </el-form-item>
        <common-group-title title="识别规则: 正则"></common-group-title>

        <el-form-item
          label="识别结果"
          class="identification"
          v-if="form.strategyType === '0'"
        ></el-form-item>
        <el-form-item
          class="identification-table"
          v-if="form.strategyType === '0'"
        >
          <common-table class="opera-table-container" :data="urlRuleData">
            <el-table-column
              label="算法名称"
              prop="ruleName"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="匹配规则"
              prop="reg"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="替换规则"
              prop="replaceReg"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column label="操作" align="left" width="80">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="deleteData(scope.$index, urlRuleData)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </common-table>
        </el-form-item>

        <el-form-item label="手动添加" class="identification btn-form-item">
          <el-button
            type="primary"
            plain
            class="addBtn"
            @click="addData('rule')"
            >新增
          </el-button>
        </el-form-item>
        <el-form-item class="identification-table">
          <common-table class="opera-table-container" :data="regRuleList">
            <el-table-column label="脱敏规则" align="left">
              <template slot-scope="scope">
                <el-select
                  style="width: 90%"
                  v-model="scope.row.ruleName"
                  size="mini"
                  clearable
                  @change="changeRuleName(scope.$index, scope.row.ruleName)"
                >
                  <el-option
                    v-for="(item, index) in ruleDataList"
                    :key="index"
                    :label="item.ruleName"
                    :value="item.ruleName"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="匹配规则"
              show-overflow-tooltip
              prop="reg"
              align="left"
            >
            </el-table-column>
            <el-table-column
              label="替换规则"
              show-overflow-tooltip
              prop="replaceReg"
              align="left"
            />
            <el-table-column label="操作" align="left" width="80">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="deleteData(scope.$index, regRuleList)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </common-table>
        </el-form-item>

        <common-group-title title="识别规则: 关键字"></common-group-title>
        <el-form-item label="手动添加" class="identification btn-form-item">
          <el-button
            type="primary"
            plain
            class="addBtn"
            @click="addData('keys')"
            >新增
          </el-button>
        </el-form-item>
        <el-form-item class="identification-table">
          <common-table class="opera-table-container" :data="keyWordRuleList">
            <el-table-column label="关键字" align="left">
              <template slot-scope="scope">
                <el-select
                  style="width: 90%"
                  v-model="scope.row.reg"
                  size="mini"
                  @change="changeKey(scope.$index, scope.row.reg)"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in keyDataList"
                    :key="index"
                    :label="item.reg"
                    :value="item.reg"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="脱敏字符"
              prop="replaceReg"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="替换类型"
              show-overflow-tooltip
              align="left"
            >
              <template slot-scope="scope">
                <span>{{ showTypeLabel(scope.row.replaceType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="left" width="80">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="deleteData(scope.$index, keyWordRuleList)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </common-table>
        </el-form-item>
        <el-button type="primary" plain @click="testForm" :loading="testLoading"
          >测试
        </el-button>
      </el-form>
      <div class="json-view" v-if="json">
        <common-json-view :json="json"></common-json-view>
      </div>
    </common-edit-dialog>
    <common-info-dialog
      :title="detailstitle"
      :visible.sync="detailsOpen"
      @cancel="cancel"
      :infoLoading="infoLoading"
    >
      <common-info-table style="margin: 0 20px; width: calc(100% - 40px)">
        <common-info-table-cell class="inof-table">
          <div class="info-table-item" style="padding-top: 12px">
            <span class="info-table-item_label">类型： </span>
            <span>{{ form.strategyType === "1" ? "通配" : "接口" }}</span>
          </div>
        </common-info-table-cell>
        <common-info-table-cell class="inof-table">
          <div class="info-table-item" style="padding-top: 12px">
            <span class="info-table-item_label">脱敏对象： </span>
            <span>{{ form.apiUrl }}</span>
          </div>
        </common-info-table-cell>
        <!-- <common-info-table-cell class="inof-table">
          <div class="info-table-item" style="padding-top: 12px">
            <span>应用名称： </span>
            <span>{{ this.form.apiName }}</span>
          </div>
        </common-info-table-cell>
        <common-info-table-cell class="inof-table">
          <div class="info-table-item" style="padding-top: 12px">
            <span>应用分类： </span>
            <span>{{ this.form.ancenstor }}</span>
          </div>
        </common-info-table-cell> -->
        <common-group-title title="识别规则: 正则"></common-group-title>
        <common-info-table-cell
          class="inof-table"
          v-if="form.strategyType === '0'"
        >
          <div>识别结果</div>
          <div class="opera-table-list">
            <common-table class="opera-table-container" :data="urlRuleData">
              <el-table-column
                label="脱敏规则"
                prop="ruleName"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="匹配规则"
                prop="reg"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="替换规则"
                prop="replaceReg"
                show-overflow-tooltip
                align="left"
              />
            </common-table>
          </div>
        </common-info-table-cell>

        <common-info-table-cell class="inof-table">
          <div>手动添加</div>
          <div class="opera-table-list">
            <common-table class="opera-table-container" :data="regRuleList">
              <el-table-column
                label="脱敏规则"
                prop="ruleName"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="匹配规则"
                prop="reg"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="替换规则"
                prop="replaceReg"
                show-overflow-tooltip
                align="left"
              />
            </common-table>
          </div>
        </common-info-table-cell>
        <common-group-title title="识别规则: 关键字"></common-group-title>

        <common-info-table-cell class="inof-table">
          <div>手动添加</div>
          <div class="opera-table-list">
            <common-table
              class="opera-table-container"
              style="margin-bottom: 12px"
              :data="keyWordRuleList"
            >
              <el-table-column
                label="关键字"
                prop="reg"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="脱敏字符"
                prop="replaceReg"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="替换类型"
                show-overflow-tooltip
                align="left"
              >
                <template slot-scope="scope">
                  <span>{{ showTypeLabel(scope.row.replaceType) }}</span>
                </template>
              </el-table-column>
            </common-table>
          </div>
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import BaseList from "@/mixins/BaseList";
import {
  addSensitive,
  deleteById,
  getInfoById,
  getRuleByUrl,
  getSensitiveList,
  getStrategyTest,
  listByType,
  selectListByUrl,
  updateForm,
  updateStatus,
} from "@/api/apisecurity/desensitization/desensitization";
import { getSingleArray, getFullDept } from "@/utils/util";
import { listLevel } from "@/api/apisecurity/applicationType/applicationType";
import { mapGetters } from "vuex";

export default {
  name: "desensitization",
  mixins: [BaseList],
  data() {
    return {
      applicationType: [],
      cascaderProps: {
        label: "orgName",
        value: "orgId",
        checkStrictly: true,
        emitPath: false,
      },
      currentParent: 3,
      infoLoading: false,
      loading: false,
      submitLoading: false,
      urlList: [],
      typeList: [
        {
          label: "启用",
          value: 0,
        },
        {
          label: "停用",
          value: 1,
        },
      ],
      showSearch: true,
      isEdit: false,
      total: 0,
      open: false,
      detailsOpen: false,
      detailstitle: "",
      multiple: true,
      urlOptions: [],
      initUrlData: [], //初始化暂存数据
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        strategyType: null,
        apiUrl: null,
        status: null,
      },
      queryParamsForOption: {
        pageNum: 1,
        pageSize: 20,
        url: "",
      },
      list: [],
      urlRuleData: [],
      regRuleList: [
        // {
        //   sensitiveId: null,
        //   ruleName: '',
        //   reg: '',
        //   replaceReg: '',
        //   groupList: '',
        //   strategyType: '0'
        // }
      ],
      ruleFieldList: [],
      keysList: [],
      keyWordRuleList: [
        // {
        //   sensitiveId: null,
        //   reg: '',
        //   replaceReg: '',
        //   strategyType: '1',
        //   replaceType: ''
        // }
      ],
      replaceTypeList: [
        {
          label: "保留前后",
          value: "0",
        },
        {
          label: "保留首位",
          value: "1",
        },
        {
          label: "保留末位",
          value: "2",
        },
        {
          label: "全部替换",
          value: "3",
        },
      ],
      form: {
        strategyType: "1",
        apiUrl: "",
        status: 1,
        deptId: "",
        apiName: "",
        ancenstor: "",
      },
      rules: {
        strategyType: [
          { required: true, message: "请选择类型", trigger: "blur" },
        ],
        apiUrl: [{ required: true, message: "请选择", trigger: "change" }],
        apiUrl2: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      isShowJson: false,
      json: null,
      testLoading: false,
      selectLoading: false,
      status: 0,
      isOpen: false,
      singleDeptList: [],
      deptListParams: [],
    };
  },
  computed: {
    ...mapGetters(["name"]),
    ruleDataList() {
      return this.ruleFieldList.reduce((r, c) => {
        let i = this.urlRuleData.findIndex((v) => v.sensitiveId === c.id),
          j = this.regRuleList.findIndex((v) => v.ruleName === c.ruleName);
        r.push({
          ...c,
          disabled: i > -1 || j > -1,
        });
        return r;
      }, []);
    },

    keyDataList() {
      return this.keysList.reduce((r, c) => {
        r.push({
          ...c,
          disabled: this.keyWordRuleList.findIndex((v) => v.reg === c.reg) > -1,
        });
        return r;
      }, []);
    },
  },
  mounted() {
    this.getList();
    this.getUrlList();
  },
  methods: {
    // 切换类型事件
    changeType() {
      this.form.apiUrl = "";
      this.keyWordRuleList = [];
      this.regRuleList = [];
      this.urlRuleData = [];
      this.isShowJson = false;
      this.json = null;
      this.$refs["form"].validateField("apiUrl");
      // this.$refs.form.fields.map((i) => {
      //     if (i.prop === "files") {
      //       i.clearValidate();
      //     }
      //   });
    },

    getLoading() {
      this.loading = true;
    },

    // 列表
    getList() {
      this.loading = true;
      getSensitiveList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
              });
              return r;
            }, []);
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => (this.loading = false));
    },
    // 查询
    handleQuery() {
      this.queryParamsForOption.url = "";
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      // this.$refs.commonDept.clearDept();
    },
    // 新增
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.isEdit = false;
      this.queryParamsForOption.url = "";
      this.queryParamsForOption.pageNum = 1;
      this.getListByType("0");
      this.getListByType("1");
    },
    // 获取apiUrl列表
    getUrlList(type, params) {
      if (type === "search") this.selectLoading = true;
      let queryParams = params ? params : this.queryParamsForOption;
      selectListByUrl(queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            if (!this.initUrlData.length) {
              this.initUrlData = [...this.initUrlData, ...res.rows];
            }
            if (type === "search") {
              this.urlOptions = res.rows;
            } else {
              if (res.rows.length > 0) {
                this.urlOptions = [...this.urlOptions, ...res.rows];
              }
            }
          } else {
            this.initUrlData = [];
          }
        })
        .finally(() => (this.selectLoading = false));
    },
    // 选择url下拉框事件
    changeUrl(val) {
      this.regRuleList = [];
      let item = this.urlOptions.find((f) => f.url === val);
      if (item) this.form.deptId = item.deptId;
      this.getInfoByUrl(val);
    },
    // 根据url获取正则规则
    getInfoByUrl(val) {
      getRuleByUrl({ apiUrl: val }).then((res) => {
        if (res && res.code === 200) {
          this.urlRuleData = res.data;
        } else {
          this.$GlobalErrorConfirm("获取失败", res.msg);
        }
      });
    },
    // 添加一条正则或者关键字
    addData(type) {
      if (type === "rule") {
        this.regRuleList.push({
          sensitiveId: null,
          ruleName: "",
          reg: "",
          replaceReg: "",
          groupList: "",
          strategyType: "0",
          replaceType: null,
          replaceMode: null,
        });
      } else {
        this.keyWordRuleList.push({
          sensitiveId: null,
          reg: "",
          replaceReg: "",
          strategyType: "1",
          replaceType: "",
          replaceMode: null,
        });
      }
    },
    // 删除正则或者关键字
    deleteData(index, list, type) {
      list.splice(index, 1);
    },

    // 根据规则类型获取脱敏规则
    getListByType(type) {
      let params = {
        strategyType: type,
      };
      return new Promise((resolve, reject) => {
        listByType(params)
          .then((res) => {
            if (res && res.code === 200) {
              if (type === "0") {
                this.ruleFieldList = res.rows.reduce((r, c) => {
                  r.push({
                    ...c,
                    disabled: false,
                  });
                  return r;
                }, []);
              } else {
                this.keysList = res.rows.reduce((r, c) => {
                  r.push({
                    ...c,
                    disabled: false,
                  });
                  return r;
                }, []);
              }
              resolve(res);
            } else {
              this.ruleFieldList = [];
              this.keysList = [];
              reject(res);
            }
          })
          .catch((err) => {
            this.ruleFieldList = [];
            this.keysList = [];
            reject(err);
          });
      });
    },

    // 脱敏规则选择事件
    changeRuleName(index, val) {
      let item = this.ruleFieldList.find((f) => f.ruleName === val);
      this.regRuleList[index].sensitiveId = item.id;
      this.regRuleList[index].reg = item.reg;
      this.regRuleList[index].replaceReg = item.replaceReg;
      this.regRuleList[index].groupList = item.groupList;
      this.regRuleList[index].replaceType = item.replaceType;
      this.regRuleList[index].replaceMode = item.replaceMode;
    },

    // 关键字选择事件
    changeKey(index, val) {
      let item = this.keysList.find((f) => f.reg === val);
      this.keyWordRuleList[index].sensitiveId = item.id;
      this.keyWordRuleList[index].replaceReg = item.replaceReg;
      this.keyWordRuleList[index].replaceType = item.replaceType;
      this.keyWordRuleList[index].replaceMode = item.replaceMode;
    },

    // 删除
    handleDelete(row) {
      if (row && row.id) {
        if (row.status === 0) {
          return this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        }
      } else {
        try {
          this.ids.forEach((f) => {
            if (this.list.find((v) => v.id === f).status === 0) {
              throw false;
            }
          });
        } catch {
          return this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        }
      }
      const ids = row.id || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          deleteById({ ids }).then((res) => {
            if (res && res.code === 200) {
              this.queryParams.pageNum = 1;

              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                ids.split(",").length === this.list.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 详情
    handleInfo(row) {
      this.detailstitle = "脱敏策略详情";
      this.detailsOpen = true;
      this.getInfoById(row.id).then();
    },
    // 修改
    handleEdit(row) {
      if (row.status === 0) {
        return this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      }
      this.resetForm();
      this.isEdit = true;
      this.open = true;
      this.queryParamsForOption.url = "";
      this.queryParamsForOption.pageNum = 1;
      this.getInfoById(row.id).then();
    },
    // 启停
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let params = {
          id: row.id,
          status: row.status,
        };
        updateStatus(params)
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              resolve(res);
              this.getList();
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
              reject();
            }
          })
          .catch(() => reject());
      });
    },
    // 取消
    cancel() {
      this.open = false;
      this.detailsOpen = false;
      this.queryParamsForOption.url = "";
      this.queryParamsForOption.pageNum = 1;
      this.resetForm();
    },
    // 提交
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (
            !this.urlRuleData.length &&
            (!this.regRuleList.length || !this.regRuleList[0].sensitiveId) &&
            (!this.keyWordRuleList.length ||
              !this.keyWordRuleList[0].sensitiveId)
          ) {
            this.$GlobalErrorConfirm(
              this.isEdit ? "编辑失败" : "新增失败",
              "正则和关键字策略内容至少填写一项"
            ).then();
            return;
          }
          let regRuleList = [],
            keyWordRuleList = [];
          if (this.regRuleList.length) {
            this.regRuleList.map((f) => {
              if (f.sensitiveId) {
                regRuleList.push({
                  sensitiveId: f.sensitiveId,
                  remark: "add",
                });
              }
            });
          }
          if (this.urlRuleData.length) {
            this.urlRuleData.map((f) => {
              if (f.sensitiveId) {
                regRuleList.push({
                  sensitiveId: f.sensitiveId,
                  remark: "discernResult",
                });
              }
            });
          }
          if (this.keyWordRuleList.length) {
            this.keyWordRuleList.map((f) => {
              if (f.sensitiveId) {
                keyWordRuleList.push({ sensitiveId: f.sensitiveId });
              }
            });
          }
          let params = {
            ...this.form,
            regRuleList: regRuleList,
            keyWordRuleList: keyWordRuleList,
          };
          if (this.isEdit) {
            this.editForm(params);
          } else {
            this.addForm(params);
          }
        }
      });
    },

    // 新增
    addForm(params) {
      this.submitLoading = true;
      addSensitive(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.open = false;
            this.queryParams.pageNum = 1;
            this.$GlobalSuccessMessage("新增成功");
            this.getList();
          } else {
            this.$GlobalErrorConfirm("新增失败", res.msg).then();
          }
        })
        .finally(() => (this.submitLoading = false));
    },

    // 编辑
    editForm(params) {
      this.submitLoading = true;
      if (params.createTime) delete params.createTime;
      updateForm(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.open = false;
            this.queryParams.pageNum = 1;
            this.$GlobalSuccessMessage("编辑成功");
            this.getList();
          } else {
            this.$GlobalErrorConfirm("编辑失败", res.msg).then();
          }
        })
        .finally(() => (this.submitLoading = false));
    },

    // 测试
    testForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.testLoading = true;
          let urlRuleData = this.urlRuleData.reduce((r, c) => {
            if (c.sensitiveId) {
              r.push({
                sensitiveId: c.sensitiveId,
                strategyType: c.strategyType,
                reg: c.reg,
                replaceReg: c.replaceReg,
                ruleName: c.ruleName,
                groupList: c.groupList,
                replaceMode: c.replaceMode,
                replaceType: c.replaceType,
                remark: "discernResult",
              });
            }
            return r;
          }, []);
          let params = {
            ...this.form,
            regRuleList: [...this.regRuleList, ...urlRuleData],
            keyWordRuleList: this.keyWordRuleList,
          };
          if (params.createTime) delete params.createTime;
          getStrategyTest(params)
            .then((res) => {
              if (res && res.code === 200) {
                this.json = res.data;
                this.isShowJson = true;
                setTimeout(() => {
                  this.$nextTick(() => {
                    this.$refs.editDialog.$refs.editDialogBody.scrollTop += 60;
                  });
                }, 100);
              } else {
                this.$GlobalErrorConfirm("测试失败", err.msg).then();
              }
            })
            .finally(() => (this.testLoading = false));
        }
      });
    },

    // 根据id获取数据
    async getInfoById(id) {
      await this.detail(id);
    },
    async detail(id) {
      this.infoLoading = true;
      await getInfoById({ id }).then((res) => {
        if (res && res.code === 200) {
          this.urlRuleData = res.data?.regRuleList.filter(
            (f) => f.remark !== "add"
          );
          // this.getInfoByUrl(res.data.apiUrl, regResultList)
          this.form = {
            ...res.data,
            strategyType: `${res.data.strategyType}`,
          };
          this.regRuleList = res.data?.regRuleList.filter(
            (f) => f.remark === "add"
          );
          this.keyWordRuleList = res.data.keyWordRuleList;

          Promise.all([this.getListByType("0"), this.getListByType("1")]).then(
            (res) => {
              if (res.length) {
                this.regRuleList.forEach((f) => {
                  f.ruleName = this.ruleFieldList.find(
                    (v) => v.id === f.sensitiveId
                  ).ruleName;
                  f.reg = this.ruleFieldList.find(
                    (v) => v.id === f.sensitiveId
                  ).reg;
                  f.replaceReg = this.ruleFieldList.find(
                    (v) => v.id === f.sensitiveId
                  ).replaceReg;
                  f.groupList = this.ruleFieldList.find(
                    (v) => v.id === f.sensitiveId
                  ).groupList;
                  f.strategyType = "0";
                });

                this.keyWordRuleList.forEach((f) => {
                  f.reg = this.keysList.find((v) => v.id === f.sensitiveId).reg;
                  f.replaceReg = this.keysList.find(
                    (v) => v.id === f.sensitiveId
                  ).replaceReg;
                  f.replaceType = this.keysList.find(
                    (v) => v.id === f.sensitiveId
                  ).replaceType;
                  f.strategyType = "1";
                });
                this.keysList.forEach((f) => {
                  f.disabled =
                    this.keyWordRuleList.findIndex((v) => v.reg === f.reg) > -1;
                });
              }
            }
          );

          this.infoLoading = false;
        } else {
          this.$GlobalErrorConfirm("获取信息失败", res.msg, "重新加载").then(
            () => {
              this.detail(id);
            }
          );
        }
      });
    },
    // 下拉框展示label
    showTypeLabel(val) {
      let index = this.replaceTypeList.findIndex((f) => f.value == val);
      return index > -1 ? this.replaceTypeList[index].label : "";
    },

    resetForm() {
      this.form = {
        strategyType: "1",
        apiUrl: "",
        status: 0,
        deptId: "",
      };
      this.keyWordRuleList = [];
      this.regRuleList = [];
      this.urlRuleData = [];
      this.isShowJson = false;
      this.json = null;
    },
    // 上拉加载
    loadMore() {
      this.queryParamsForOption.pageNum++;
      this.getUrlList();
    },
    focus(val) {
      if (!this.form.apiUrl) {
        this.urlOptions = this.initUrlData;
      }
    },
    // 下拉框远程搜索
    remoteMethod(query) {
      this.queryParamsForOption.url = query;
      let params = {
        ...this.queryParamsForOption,
        pageNum: 1,
      };
      this.getUrlList("search", params);
    },
  },
};
</script>
<style lang="scss" scoped>
.btn-form-item {
  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: flex-end;
  }
}

.identification {
  margin-bottom: 0;
}

.identification-table {
  ::v-deep .el-form-item__content {
    margin-left: 20px !important;
  }
}

.inof-table {
  ::v-deep .info-table-row-label {
    width: 0px !important;
    padding-right: 0 !important;
  }

  ::v-deep .info-table-row-value {
    width: 100% !important;
  }
}

.json-view {
  margin-top: 12px;
}

.opera-table-list {
  height: 200px;
  padding: 0 18px;
  margin-bottom: 18px;
  box-sizing: border-box;
  overflow-y: scroll;
}

::v-deep .opera-table-container {
  border: 1px solid #eee;
  border-bottom: 0;
  line-height: 0;
}

::v-deep .global-info-table-row-wrap {
  border-bottom: none !important;
}

.info-table-item {
  display: flex;
  align-items: center;

  .info-table-item_label {
    width: 70px;
    text-align: right;
  }
}

::v-deep .el-switch__label {
  font-weight: normal;
}

::v-deep .icon-xitongpeizhi {
  speak: none !important;
  font-style: normal !important;
  font-weight: 400 !important;
  font-variant: normal !important;
  text-transform: none !important;
  line-height: 1 !important;
  vertical-align: baseline !important;
  display: inline-block !important;
  -webkit-font-smoothing: antialiased !important;
  font-size: 12px;
  margin-right: 5px;
}
</style>
